package com.hznu.coursemanagerbackend.modules.sys.controller;


import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.google.api.client.util.Value;
import com.hznu.coursemanagerbackend.common.utils.FileUtils;
import com.hznu.coursemanagerbackend.common.utils.PageUtils;
import com.hznu.coursemanagerbackend.common.validator.Assert;
import com.hznu.coursemanagerbackend.modules.sys.bean.AddStudentsBean;
import com.hznu.coursemanagerbackend.modules.sys.bean.CourseStudentLoadDto;
import com.hznu.coursemanagerbackend.modules.sys.bean.UserLoadDto;
import com.hznu.coursemanagerbackend.modules.sys.service.*;
import com.hznu.coursemanagerbackend.modules.sys.entity.*;
import com.hznu.coursemanagerbackend.myBeans.R;
import com.xuxueli.poi.excel.ExcelImportUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import org.springframework.stereotype.Controller;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.lang.Class;
import java.util.List;
import java.util.Map;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author DragonDoor
 * @since 2018-11-12
 */
@EnableAutoConfiguration //自动载入应用程序所需的所有Bean
@RestController //@Controller与@ResponseBody的合并
@RequestMapping("/courseStudent")
@Api(description = "教师所授课程与学生关联接口", value = "CourseStudent")
public class CourseStudentController extends AbstractController{

    @Autowired
    CourseStudentService courseStudentService;

    @Autowired
    CourseTeachService courseTeachService;

    @Autowired
    CourseService courseService;

    @Autowired
    UserService userService;

    @Autowired
    StudentInfoService studentInfoService;

    @Autowired
    TeacherInfoService teacherInfoService;

    @Autowired
    ClassService classService;

    @Value("${template.courseStudentTemplatepath}")
    private String courseStudentTemplatepath = "上课学生导入模板.xls";

    /**
     * @author Wqd
     * @since 2018-12-6
     */
    @ApiOperation("单个加入学生名单")
    @PostMapping("/addOne")
    public R addOne(@RequestBody CourseStudentLoadDto courseStudentLoadDto){
        try{
                    User user = userService.selectOne(new EntityWrapper<User>().eq("workid",courseStudentLoadDto.getWorkId()));
            if(user!=null){    //已存在该学生的记录
                StudentInfo studentInfo1 = studentInfoService.selectOne(new EntityWrapper<StudentInfo>().eq("userid",user.getId()));
                CourseStudent courseStudent = new CourseStudent();
                courseStudent.setCourseteachid(courseStudentLoadDto.getCourseteachid());
                courseStudent.setStudentid(studentInfo1.getId());
                if(courseStudentService.selectOne(new EntityWrapper<CourseStudent>().eq("courseteachid",courseStudent.getCourseteachid()).eq("studentid",courseStudent.getStudentid()))==null){
                    courseStudentService.insert(courseStudent);
                }else{
                    return R.error("授课班中已存在该学生");
                }
            }else { //尚未存在该学生记录
                return R.error("无该学生记录，请联系管理员添加");
            }
            return R.ok();
        }catch (Exception e){
            e.printStackTrace();
            return R.error();
        }
    }
    /**
     * @author: DragonDoor
     * @Date: 2018/12/17 10:41
     * @Description: 
     */
    @ApiOperation("按照课程教师id及关键字条件查找学生")
    @PostMapping("/findStudentsByCondition")
    public R findStudentsByCondition(@RequestParam Map<String,Object> params) {
        PageUtils page = courseStudentService.queryPageByCourseteachid(params);
        return R.ok().put("page", page);
    }

    /**
     * @Description: 上课学生批量导入模板下载
     * @param:
     * @return:
     * @author: TateBrown
     * @Date: 2018/12/24
     */
    @ApiOperation("下载批量导入用户的模板")
    @GetMapping("/downloadtemplate")
    public ResponseEntity<byte[]> downloadTemplate(HttpServletRequest request){
        try{
            byte[] data= FileUtils.ConvertFiletoByte(courseStudentTemplatepath);
            HttpHeaders headers=new HttpHeaders();
            String filename=new String("上课学生导入模板.xls".getBytes("UTF-8"),"iso-8859-1");
            headers.setContentDispositionFormData("attachment",filename);
            headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
            org.springframework.http.HttpStatus statusCode= org.springframework.http.HttpStatus.OK;
            return new ResponseEntity<byte[]>(data,headers,statusCode);
        }catch(Exception e){
            logger.error(e.toString());
            return null;
        }
    }

    /**
     * @Description: 上课学生批量导入
     * @param:
     * @return:
     * @author: TateBrown
     * @Date: 2018/12/24
     */
     @ApiOperation("上课学生批量导入")
     @PostMapping("/LoadcourseStudent/{courseTeachid}")
     public  R LoadcourseStudent(@PathVariable Integer courseTeachid, @RequestParam("file")MultipartFile file){
         try{
             String Suffix=FileUtils.getSuffix(file.getOriginalFilename());
             if(!Suffix.equals(".xls")){
                 return R.error("上传失败，请检查文件后缀，仅支持xls格式的Excel");
             }
             List<Object> StudentDtoList= ExcelImportUtil.importExcel(CourseStudentLoadDto.class,file.getInputStream());
             Assert.isNull(StudentDtoList,"导入学生为空");
             Integer count=courseStudentService.LoadBatch(StudentDtoList,courseTeachid);
             return R.ok("添加完成，共添加了"+count+"条");
         }catch(Exception e){
         logger.error(e.toString());
         return R.error();
         }
     }

    /**
     * @Description:授课班添加整个班级
     * @param:
     * @return:
     * @author: Wqd
     * @Date: 2019/3/11
     */
    @ApiOperation("授课班添加整个班级")
    @PostMapping("/addClass/{classid}/{courseteachid}")
    public R addClass(@PathVariable Integer classid,@PathVariable Integer courseteachid) {
        try {
            List<StudentInfo> studentInfoList = studentInfoService.selectList(new EntityWrapper<StudentInfo>().eq("classid",classid));
            for(StudentInfo studentInfo : studentInfoList){
                if(courseStudentService.selectOne(new EntityWrapper<CourseStudent>().eq("courseteachid",courseteachid).eq("studentid",studentInfo.getId()))==null){
                    CourseStudent courseStudent = new CourseStudent();
                    courseStudent.setCourseteachid(courseteachid);
                    courseStudent.setStudentid(studentInfo.getId());
                    courseStudentService.insert(courseStudent);
                }
            }
            return R.ok("添加成功！");
        } catch (Exception e) {
            e.printStackTrace();
            return R.error();
        }
    }

    /**
     * @Description:授课班添加多个学生
     * @param:
     * @return:
     * @author: Wqd
     * @Date: 2019/4/10
     */
    @ApiOperation("授课班添加多个学生")
    @PostMapping("/addStudents")
    public R addStudents(@RequestBody AddStudentsBean addStudentsBean) {
        try {
            for(String workid : addStudentsBean.getWorkidList()){
                CourseStudent courseStudent = new CourseStudent();
                User user = userService.selectOne(new EntityWrapper<User>().eq("workid",workid));
                courseStudent.setStudentid(studentInfoService.selectOne(new EntityWrapper<StudentInfo>().eq("userid",user.getId())).getId());
                courseStudent.setCourseteachid(addStudentsBean.getCourseteachid());
                if(courseStudentService.selectCount(new EntityWrapper<CourseStudent>().eq("courseteachid",addStudentsBean.getCourseteachid()).eq("studentid",courseStudent.getStudentid()))==0){
                    courseStudentService.insert(courseStudent);
                }
            }
            return R.ok("添加成功！");
        } catch (Exception e) {
            e.printStackTrace();
            return R.error();
        }
    }

}

